package com.yu.thread6;

import java.util.concurrent.TimeUnit;

/**
 * Created by xiaolongyu on 15/3/28.
 */
public class InterruptingIdiom {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Blocked3());
        t.start();

        new Thread(new Caluation()).start();
        TimeUnit.MILLISECONDS.sleep(1100);
        System.out.println("interrupt start:" + System.currentTimeMillis());
        t.interrupt();
        System.out.println("interrupt end:" + System.currentTimeMillis());

        TimeUnit.SECONDS.sleep(5);
        int d = 0;
        d = (int) ((200) / d);
        System.out.println("==>d:" + d);
        System.exit(0);
    }
}

class NeedsCleanUp{
    private final int id;

    public NeedsCleanUp(int ident){
        id = ident;
        System.out.println("NeedsCleanup " + id);
    }

    public void cleanup(){
        System.out.println("Cleaning up " + id);
    }
}

class Caluation implements Runnable{
    private volatile double d = 1.0;
    @Override
    public void run() {
        System.out.println("d:" + d);
        while(true){
            d = (Math.PI + Math.E) / d;
//            try {
//                TimeUnit.MILLISECONDS.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            Thread.yield();
        }
    }
}

class Blocked3 implements Runnable{
    private volatile double d = 0.0;

    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                NeedsCleanUp n1 = new NeedsCleanUp(1);

                try {
                    System.out.println("Sleep");
                    TimeUnit.SECONDS.sleep(1);
                    NeedsCleanUp n2 = new NeedsCleanUp(2);

                    try {
                        System.out.println("Calculating:" + System.currentTimeMillis());
                        System.out.println("-->d:" + d);
                        for(int i = 1; i < 250000; i ++){
                            d = d + (Math.PI + Math.E) / d;
                            Thread.yield();
                        }
                        System.out.println("Finished time-consuming operation:" + System.currentTimeMillis());
                    } finally {
                        n2.cleanup();
                    }
                } finally {
                    n1.cleanup();
                }
                System.out.println("-------------------------------");
            }
            System.out.println("Exiting via while() test");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println("Exit via Exception");
        }
    }
}
